<?php

class HistoryBehavior extends CActiveRecordBehavior
{
//	private $_oldattributes = array();
	
    public function beforeSave($event)
    {
		if ($this->owner->isNewRecord) return;
		Yii::trace(get_class($this->getOwner()).'.'.get_class($this).'.beforeSave()','app.components.behaviors');
		
		$oldattributes = $this->Owner->getOldAttributes();
		$newattributes = $this->Owner->getAttributes();
		
		$admin_id = (get_class(Yii::app())=='CConsoleApplication') ? 9999 : Yii::app()->user->id;
		if (Yii::app()->user->getState('role')==0) $admin_id=9999;
		$admin_ip = (get_class(Yii::app())=='CConsoleApplication') ? NULL : Yii::app()->request->userHostAddress;
		
		foreach ($newattributes as $name => $value)
		{
			if ($name=='update_time') continue;
		
			if (!empty($oldattributes)) {
				$old = $oldattributes[$name];
			} else {
				$old = '';
			}

			if ($value != $old)
			{
				$history = new History;
				if ($name!='is_active') $history->status = History::STATUS_UPDATE;
				else $history->status = $value == 0 ? History::STATUS_DELETE : History::STATUS_UNDELETE;
				$history->table = get_class($this->owner);
				$history->id_id = $this->owner->id;
				$history->column = $name;
				$history->value = $old;
				$history->new_value = $value;
				$history->admin_id = $admin_id;
				$history->admin_ip = $admin_ip;
				$history->save();
			}
		}
    }
    
    public function afterSave($event)
    {
		if (!$this->owner->isNewRecord) return;
		Yii::trace(get_class($this->getOwner()).'.'.get_class($this).'.afterSave()','app.components.behaviors');
		
		$newattributes = $this->Owner->getAttributes();
		
		$admin_id = (get_class(Yii::app())=='CConsoleApplication') ? 9999 : Yii::app()->user->id;
		$admin_ip = (get_class(Yii::app())=='CConsoleApplication') ? NULL : Yii::app()->request->userHostAddress;
		
		foreach ($newattributes as $name => $value)
		{
			if (in_array($name,array('update_time','create_time','is_active'))) continue;
			
			if ($value!=='' or $value!==null)
			{
				$history = new History;
				$history->status = History::STATUS_ADD;
				$history->table = get_class($this->owner);
				$history->id_id = $this->owner->id;
				$history->column = $name;
				$history->new_value = $value;
				$history->admin_id = $admin_id;
				$history->admin_ip = $admin_ip;
				$history->save();
			}
		}
    }

//    public function afterFind($event)
//    {
//        // Save old values
//        Yii::trace(get_class($this->getOwner()).'.'.get_class($this).'.afterFind()','app.components.behaviors');
//        $this->setOldAttributes($this->Owner->getAttributes());
//    }
//
//    public function getOldAttributes()
//    {
//        return $this->_oldattributes;
//    }
//
//    public function setOldAttributes($value)
//    {
//    	Yii::trace(get_class($this->getOwner()).'.'.get_class($this).'.setOldAttributes()','app.components.behaviors');
//        $this->_oldattributes=$value;
//    }

}